package com.dounine.clouddisk360.parser;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dounine.clouddisk360.parser.deserializer.diffpre.DifferPress;
import com.dounine.clouddisk360.parser.deserializer.diffpre.DifferPressConfig;
import com.dounine.clouddisk360.parser.deserializer.diffpre.DifferPressConst;
import com.dounine.clouddisk360.parser.deserializer.diffpre.DifferPressRequestInterceptor;
import com.dounine.clouddisk360.parser.deserializer.diffpre.DifferPressResponseHandle;
import com.dounine.clouddisk360.pool.PoolingHttpClientConnection;
import com.dounine.clouddisk360.util.TimeUtil;

public class DifferPressParser extends BaseParser<DifferPressConfig> {

	private static final Logger LOGGER = LoggerFactory.getLogger(DifferPressParser.class);
	public static final String DIFFER_PRESS_URL = "http://yunpan.360.cn/user/login";

	@Override
	public void initConfig(DifferPressConfig differPressConfig) {
		super.initConfig(differPressConfig);// 必需调用父类的initConfig方法,或者重写里面所定义的cookieStore路径
	}

	public DifferPress parse(DifferPressConfig config) {
		HttpGet request = initRequest();
		return this.execute(request);
	}
	
	public HttpGet initRequest(){
		try {
			URIBuilder uri = new URIBuilder(DIFFER_PRESS_URL);
			uri.addParameter(DifferPressConst.ST_KEY, TimeUtil.getTimeLenth(10));
			uri.addParameter(DifferPressConst.SID_KEY, StringUtils.EMPTY);
			uri.addParameter(DifferPressConst.KEEPALIVE_KEY, DifferPressConst.KEEPALIVE_VAL);
			HttpGet request = new HttpGet(uri.build());
			return request;
		} catch (URISyntaxException e) {
			LOGGER.error("生成分压请求对象失败");
		}
		return null;
	}

	public DifferPress execute(HttpGet request) {
		super.httpClient = HttpClients.custom()
				.setConnectionManager(PoolingHttpClientConnection.getInstalce())
				.addInterceptorLast(new DifferPressRequestInterceptor())
				.setDefaultCookieStore(readCookieStoreDisk())
				.build();
		
		RequestConfig differPressConfig = RequestConfig.copy(cookieRequestConfig())
				.setCookieSpec(CookieSpecs.NETSCAPE)
				.setRedirectsEnabled(false)
				.build();//use my config
		request.setConfig(differPressConfig);
		try {
			return super.httpClient.execute(request,new DifferPressResponseHandle(super.httpClientContext), super.httpClientContext);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
